package com.iflytek.ci.cpms.service.impl;

import com.iflytek.ci.common.service.MilestoneMailService;
import com.iflytek.ci.common.utils.excel.Excels;
import com.iflytek.ci.cpms.dao.MilestoneBatchDao;
import com.iflytek.ci.cpms.dao.MilestoneDao;
import com.iflytek.ci.cpms.dao.ProjectDao;
import com.iflytek.ci.cpms.domain.Milestone;
import com.iflytek.ci.cpms.dto.MilestoneReport;
import com.iflytek.ci.cpms.dto.ProjectInformation;
import com.iflytek.ci.cpms.service.MilestoneService;
import com.iflytek.ci.cpms.service.util.IssueImportExcelParser;
import com.iflytek.ci.cums.service.impl.ShiroDbRealm;
import com.iflytek.ci.qams.dto.IssueExcel;
import com.iflytek.framework.pagination.PaginationCriteria;
import com.iflytek.framework.pagination.PaginationResult;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("MilestoneService")
@Transactional(readOnly = true)
public class MilestoneServiceImpl implements MilestoneService {
	/** 日志 */
	private static final Logger LOGGER = LoggerFactory
			.getLogger(MilestoneService.class);
	/** 里程碑的数据库服务 */
	@Autowired
	private MilestoneDao milestoneDao;
	@Autowired
	private ProjectDao projectDao;
	@Autowired
	private MilestoneMailService milestoneMailService;
	@Autowired
	private MilestoneBatchDao milestoneBatchDao;

	@Transactional
	@Override
	public void add_new(Milestone milestone) {
		ShiroDbRealm.ShiroUser shiro = (ShiroDbRealm.ShiroUser) SecurityUtils
				.getSubject().getPrincipal();
		milestone.setCreateTime(new Date());
		milestone.setCreateUser(shiro.getId());
		milestone.setUserName(shiro.getName());
		milestoneDao.add_new_milestone(milestone);
		ProjectInformation projectinfo = projectDao
				.getPrjectInformation(milestone.getProject());
		milestoneMailService.new_milestone(projectinfo, milestone, null);
	}

	@Transactional
	@Override
	public void delete_with_id(long id) {
		milestoneDao.remove_milestone_id(id);
	}

	@Override
	public List<Milestone> milestones_advanced_query(long projectId,
			Map<String, Object> params) {
		return milestoneDao.get_milestone_with(projectId, params);
	}

	@Transactional
	@Override
	public void delete_with_project(long id) {
		milestoneDao.remove_milestone_pid(id);
	}

	@Override
	public Milestone get_milestone_id(long id) {
		return milestoneDao.find_milestone_with_id(id);
	}

	@Override
	public List<Milestone> get_milestones_project(long p_id) {
		return milestoneDao.find_milestone_project(p_id);
	}

	@Transactional
	@Override
	public void update_milestone(Milestone milestone) {
		// ShiroDbRealm.ShiroUser
		// shiro=(ShiroDbRealm.ShiroUser)SecurityUtils.getSubject().getPrincipal();
		milestoneDao.update_milestone(milestone);
	}

	@Transactional
	@Override
	public void set_milestone_reach(String description, long id) {
		// TODO 添加邮件回复，发送里程碑报告
		milestoneDao.update_finish(description, id);
		// milestoneMailService.reach_milestone(milestoneDao.find_milestone_with_id(id),
		// null);
	}

	@Override
	public PaginationResult<Milestone> get_milestone(
			PaginationCriteria criteria, long project_id) {
		if (project_id == 0) {
			return milestoneDao.page_all_milestone(criteria);
		} else {
			return milestoneDao.page_pro_milestone(criteria, project_id);
		}
	}

	@Transactional
	@Override
	public void remove_milestone_pids(String[] p_ids) {
		milestoneDao.delete_with_pids(p_ids);
	}

	@Transactional
	@Override
	public boolean remove_milestone_ids(long[] ids) {
		Object milestone = milestoneDao.get_issue_top(ids);
		if (milestone == null) {
			milestoneDao.remove_milestone(ids);
			return true;
		} else {
			LOGGER.debug("里程碑已存在反馈，无法删除");
			return false;
		}
	}

	@Transactional(isolation = Isolation.READ_UNCOMMITTED)
	@Override
	public void update_milestone_counts(long milestone_id, long[] ids) {
		milestoneBatchDao.update_cate_count(milestone_id, ids);
		milestoneDao.update_counts(milestone_id, ids.length);
	}

	@Override
	public List<Milestone> all_milestone() {
		return milestoneDao.all_milestone();
	}

	@Override
	public void cate_count_update(long[] ids, int status) {
		if (status == 0) {
			milestoneBatchDao.reopen_cate_count(ids);
		} else if (status == 1) {
			milestoneBatchDao.close_cate_count(ids);
		}
	}

	@Override
	public void send_milestone_report(MilestoneReport milestoneReport) {
		milestoneMailService.send_milestone_report_mail(milestoneReport);
	}

	@Transactional(isolation = Isolation.READ_UNCOMMITTED)
	@Override
	public String issue_import(MultipartFile upload_file) {
		File file = null;
		String texaArea = "";
		try {
			String temp_file_path = System.getProperty("java.io.tmpdir")
					+ File.separator + upload_file.getOriginalFilename();
			file = new File(temp_file_path);
			FileUtils.writeByteArrayToFile(file, upload_file.getBytes());
			List<IssueExcel> list = (List<IssueExcel>) Excels.readExcel(0,
					new IssueImportExcelParser(), temp_file_path);

			for (IssueExcel issueExcel : list) {
				if (issueExcel.getResolve_way().equals("延迟解决")) {
					texaArea += issueExcel.getSn() + " " + issueExcel.getNo()
							+ " " + issueExcel.getTitle() + " "
							+ issueExcel.getProject() + " "
							+ issueExcel.getModule() + " "
							+ issueExcel.getFind_way() + " "
							+ issueExcel.getSeverity() + " "
							+ issueExcel.getPriopity() + " "
							+ issueExcel.getStatus() + " "
							+ issueExcel.getResolve_way() + " "
							+ issueExcel.getAssigner() + " "
							+ issueExcel.getUpdate_date() + " "
							+ issueExcel.getDuration() + " "
							+ issueExcel.getCreator() + " "
							+ issueExcel.getCreate_date() + " "
							+ issueExcel.getFind_version() + " "
							+ issueExcel.getResolve_version() + ";" + "\n";
					System.out.println(texaArea);
				}
			}
		} catch (Exception e) {
			LOGGER.error("导入用户数据时文件上传出现异常!", e);

		} finally {

		}
		return texaArea;
	}
}
